<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function myAxios(option) {
        // console.log(option);
        const { method = "get", params, data } = option;
        let { url } = option;
        // 将对象转换为 ?a=100&b=200
        if (method === "get") {
          const arr = [];
          for (const k in params) {
            const value = params[k];
            arr.push(`${k}=${value}`);
          }
          // console.log(arr);
          const queryString = arr.join("&");
          url += `?${queryString}`;
          console.log(url);
        }
        return new Promise((resolve, reject) => {
          // 处理异步任务
          // 原生 ajax
          const xhr = new XMLHttpRequest();
          xhr.open(method, url);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.addEventListener("load", () => {
            // 将成功的结果交给 resolve
            // console.log(xhr.response);
            resolve(xhr.response);
          });
          xhr.send(JSON.stringify(data));
        });
      }

      myAxios({
        method: "get",
        url: "http://ajax-api.itheima.net/api/robot",
        params: {
          spoken: "你吃了吗？",
          // a: "123",
          // b: "456",
        },
      }).then((res) => {
        const data = JSON.parse(res);
        console.log(data);
      });
    </script>
  </body>
</html>
